<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>群聊</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
    <script src="/js/sockjs.min.js"></script>
    <script src="/js/stomp.min.js"></script>
</head>
<body>

<table>
    <tr>
        <td>请输入用户名</td>
        <td><input type="text" id="name"></td>
    </tr>
    <tr>
        <td><input type="button" id="connect" value="连接"></td>
        <td><input type="button" id="disconnect" disabled="disabled" value="断开连接"></td>
    </tr>
</table>

<div id="chat" style="display: none">
    <table>
        <tr>
            <td>请输入聊天内容</td>
            <td><input type="text" id="content"></td>
            <td><input type="button" id="send" value="发送"></td>
        </tr>
    </table>
    <div id="conversation">群聊进行中...</div>
</div>
</body>
<script>
    $(function(){
        $("#connect").click(function(){
            connect();
        })
    })

    $("#disconnect").click(function () {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
    })

    $("#send").click(function () {
        //将消息发送到代理方法内
        stompClient.send('/app/hello',{},JSON.stringify({'name':$("#name").val(),'content':$("#content").val()}))
    })

    var stompClient = null;

    function connect(){
        if (!$("#name").val()) {
            return;
        }
        //建立连接
        var socket = new SockJS('/chat');
        stompClient = Stomp.over(socket);
        stompClient.connect({},function(success){
            setConnected(true);
            stompClient.subscribe('/topic/greetings', function (msg) {
                //拿到输入的消息内容进行展示
                showGreeting(JSON.parse(msg.body));
            });
        })
    }

    //展示消息的内容
    function showGreeting(msg) {
        $("#conversation").append('<div>' + msg.name + ':' + msg.content + '</div>');
    }

    //设置连接按钮，已经连接上则禁止，反之不禁止
    function setConnected(flag){
        $("#connect").prop("disabled", flag);
        $("#disconnect").prop("disabled", !flag);
        if (flag) {
            $("#chat").show();
        } else {
            $("#chat").hide();
        }
    }
</script>
</html>
